<template>
  <t-modal
    :title="title"
    width="1048px"
    :visible="visible"
    @cancel="closeModal()"
    @ok="onSubmit()"
    wrapClassName="add-modal-container"
    v-bind="footer"
    forceRender
    :confirmLoading="submitLoading"
  >
    <div class="curve-modal-body">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="isDisabled"
      >
        <a-form-model-item label="项目名称" prop="tenantCode">
          <a-select
            placeholder="请选择"
            v-model="form.tenantCode"
            showSearch
            :filter-option="filterOption"
            :disabled="isDisabled"
          >
            <a-select-option
              :value="item.proCode"
              v-for="item in projectSoucre"
              :key="item.uuid"
            >
              {{ item.proName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="项目类型" prop="engType">
              <a-select
                allowClear
                placeholder="请选择"
                v-model="form.engType"
                showSearch
                :filter-option="filterOption"
                :disabled="isDisabled"
              >
                <a-select-option
                  :value="item.dicItemCode"
                  v-for="item in engineerTypeSourec"
                  :key="item.dicItemCode"
                >
                  {{ item.dicItemName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="立项类型" prop="type">
              <a-select
                allowClear
                placeholder="请选择"
                v-model="form.type"
                showSearch
                :filter-option="filterOption"
                :disabled="isDisabled"
              >
                <a-select-option
                  :value="item.dicItemCode"
                  v-for="item in approvalTypeSourec"
                  :key="item.dicItemCode"
                >
                  {{ item.dicItemName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item label="区域" prop="workArea">
          <a-cascader
            :options="provinceSource"
            :field-names="{
              label: 'name',
              value: 'name',
              children: 'children',
            }"
            placeholder="请选择"
            v-model="form.workArea"
            :disabled="isDisabled"
          />
        </a-form-model-item>
        <a-form-model-item
          :key="index"
          v-for="(item, index) in form.childList"
          :label="item.name"
          :prop="'childList.' + index + '.files'"
          :rules="{
            required: isDisabled ? false : true,
            message: '请选择' + item.name,
          }"
        >
          <bjUploadFile
            :viewMode="isDisabled"
            :count="20"
            v-model="item.files"
            @preview="viewFile($event)"
            @download="downloadFile($event)"
            @change="
              handleUpLoadFile($event, {
                idx: index,
                domain: 'files',
              })
            "
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-textarea
            placeholder="请输入"
            :rows="4"
            v-model="form.remark"
            :disabled="isDisabled"
          />
        </a-form-model-item>
        <a-row :gutter="0" v-if="isDisabled">
          <a-col :span="12">
            <a-form-model-item label="创建人">
              <a-input :rows="4" v-model="form.creator" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="创建时间">
              <a-input :rows="4" v-model="form.createTime" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </t-modal>
</template>

<script>
import { mapGetters } from "vuex";
import { axios } from "@/utils/request";
import { getToken, downloadDfs } from "@/utils/TopVUI";
import areaData from "@/components/_utils/area-json.js";
//附件上传
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
import { getDicItemByCode, getAllProListByQX } from "@/api/common.js";
import { detailCanton, saveCanton } from "@/api/cantonManage";
export default {
  components: {
    bjUploadFile,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    operateType: {
      type: [String, Number],
      default: 1,
    },
    parameter: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      title: "新增",
      footer: {},
      isDisabled: false,
      submitLoading: false,
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
      form: {
        uuid: "",
        //项目名称
        tenantCode: undefined,
        //项目类型
        engType: undefined,
        //立项类型
        type: undefined,
        //区域
        workArea: [],
        //文件
        childList: [],
        //备注
        remark: "",
        //创建人
        creator: "",
        //创建时间
        createTime: "",
      },
      rules: {
        tenantCode: [
          {
            required: true,
            message: "请选择项目名称",
          },
        ],
        engType: [
          {
            required: true,
            message: "请选择项目类型",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择立项类型",
          },
        ],
        workArea: [
          {
            required: true,
            message: "请选择区域",
          },
        ],
      },
      //省市区
      provinceSource: areaData,
      //项目名称
      projectSoucre: [],
      //项目类型
      engineerTypeSourec: [],
      //立项类型
      approvalTypeSourec: [],
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.filterTitle();
          this.getData();
        }
      },
      immediate: true,
    },
  },

  methods: {
    //查询数据
    async getData() {
      //项目
      await this.getProjectData();
      //项目类型
      this.engineerTypeSourec = await this.getDicCodeData("engineeringType");
      //立项类型
      this.approvalTypeSourec = await this.getDicCodeData(
        "projectApprovalType"
      );
      this.getDetail();
    },

    //查询所有项目
    getProjectData() {
      return new Promise((resolve, reject) => {
        getAllProListByQX()
          .then((res) => {
            this.projectSoucre = res?.data ?? [];
            resolve();
          })
          .catch((_) => {
            this.projectSoucre = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //
    filterTitle() {
      let { operateType } = this;
      switch (operateType) {
        case 1:
          this.title = "新增";
          this.footer = {};
          this.isDisabled = false;
          break;

        case 2:
          this.title = "编辑";
          this.footer = {};
          this.isDisabled = false;
          break;

        case 3:
          this.title = "详情";
          this.footer = { footer: null };
          this.isDisabled = true;
          break;

        default:
          break;
      }
    },

    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { form } = this;
          let formJson = {
            uuid: form.uuid,
            //项目名称
            tenantCode: form.tenantCode,
            //项目类型
            engType: form.engType,
            //立项类型
            type: form.type,
            //区域
            workArea: form?.workArea.join("@"),
            //文件
            list: [],
            //备注
            remark: form.remark,
          };
          form.childList.forEach((item) => {
            const fileList = item.files.map(
              ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
            );
            formJson.list.push({
              uuid: item.detailId,
              name: item.name,
              files: JSON.stringify(fileList),
            });
          });
          this.submitLoading = true;
          saveCanton(formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("处理成功", 1.5);
                this.$parent.getTableData();
                this.closeModal();
              } else {
                this.$message.error(res?.message ?? "处理失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.submitLoading = false;
            });
        }
      });
    },

    //下载
    downloadFile(row) {
      let { url } = row;
      downloadDfs(url);
    },

    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    //上传附件
    handleUpLoadFile({ file, index }, item) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      let { idx, domain } = item;
      this.$set(this.form["childList"][idx][domain][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(
            this.form["childList"][idx][domain][index],
            "dfsFileUuid",
            res.dfsFileUuid
          );
          this.$set(this.form["childList"][idx][domain][index], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form["childList"][idx][domain][index], "fail", true);
        })
        .finally((_) => {
          this.$set(
            this.form["childList"][idx][domain][index],
            "loading",
            false
          );
        });
    },

    //详情
    getDetail() {
      let { uuid } = this.parameter;
      detailCanton({
        uuid,
        code: "XMLX",
      })
        .then((res) => {
          this.form = {
            //批注id
            uuid: res?.uuid ?? "",
            //项目名称
            tenantCode: res?.tenantCode,
            //项目类型
            engType: res?.engType,
            //区域
            workArea: res?.workArea.split("@") ?? [],
            //立项类型
            type: res?.type,
            //文件
            childList: res?.childList ?? [],
            //备注
            remark: res.remark,
            //创建人
            creator: res.creator,
            //创建湿巾
            createTime: res.createTime,
          };
          this.form.childList.forEach((item) => {
            item.files = JSON.parse(item.files ?? "[]");
          });
        })
        .catch((_) => {});
    },

    //重置表单
    resetForm() {
      this.form = {
        uuid: "",
        //项目名称
        tenantCode: undefined,
        //项目类型
        engType: undefined,
        //立项类型
        type: undefined,
        //区域
        workArea: [],
        //文件
        childList: [],
        //备注
        remark: "",
        //创建人
        creator: "",
        //创建湿巾
        createTime: "",
      };
      this.$refs.ruleForm.resetFields();
    },

    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
    .curve-modal-body {
      box-sizing: border-box;
      padding: 14px 70px 14px 40px;
      max-height: 700px;
      overflow: auto;
      .ant-form-item {
        display: flex;
        .ant-form-item-label {
          flex-shrink: 0;
          width: 140px;
          label {
            color: #333333;
          }
        }
        .ant-form-item-control-wrapper {
          flex: 1;
          overflow: hidden;
        }
      }
      .bj-upload-file {
        .choosed-file-warp {
          width: 100%;
        }
      }
    }
  }
}
</style>
